package com.shanzhu.parking.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shanzhu.parking.entity.Card;
import com.shanzhu.parking.entity.query.CardQuery;
import com.shanzhu.parking.mapper.CardMapper;
import com.shanzhu.parking.mapper.UserMapper;
import com.shanzhu.parking.service.ICardService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * IC卡服务实现类
 */
@Service
@RequiredArgsConstructor
public class CardServiceImpl extends ServiceImpl<CardMapper, Card> implements ICardService {
    
    private final UserMapper userMapper;

    @Override
    public IPage<Card> getCardList(CardQuery cardQuery) {
        // 构建查询条件
        LambdaQueryWrapper<Card> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加卡号模糊查询条件
        if (StrUtil.isNotBlank(cardQuery.getCardNo())) {
            queryWrapper.like(Card::getCardNo, cardQuery.getCardNo());
        }
        
        // 添加卡片状态条件
        if (cardQuery.getStatus() != null) {
            // 状态转换：1-正常，2-挂失，3-注销
            String status = null;
            switch (cardQuery.getStatus()) {
                case 1:
                    status = "正常";
                    break;
                case 2:
                    status = "挂失";
                    break;
                case 3:
                    status = "注销";
                    break;
            }
            
            if (status != null) {
                queryWrapper.eq(Card::getCardStatus, status);
            }
        }
        
        // 创建分页对象
        Page<Card> page = new Page<>(cardQuery.getPagenum(), cardQuery.getPageSize());
        
        // 执行分页查询
        return page(page, queryWrapper);
    }

    @Override
    public boolean checkCardNoExists(String cardNo) {
        if (StrUtil.isBlank(cardNo)) {
            return false;
        }
        
        return count(Wrappers.<Card>lambdaQuery().eq(Card::getCardNo, cardNo)) > 0;
    }

    @Override
    public List<Object> searchUsers(String query) {
        // 这里应该实现搜索用户的逻辑
        // 由于没有提供User类的具体实现，这里返回空列表
        // 实际项目中应该调用UserMapper查询用户
        if (StrUtil.isBlank(query)) {
            return Collections.emptyList();
        }
        
        // 模拟返回结果
        return new ArrayList<>();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Card openCard(String username, String cardNo, String icType, Double balance) {
        if (StrUtil.isBlank(cardNo) || StrUtil.isBlank(username)) {
            return null;
        }
        
        // 检查卡号是否已存在
        if (checkCardNoExists(cardNo)) {
            return null;
        }
        
        // 这里应该查询用户ID
        // 由于没有提供User类的具体实现，这里使用默认值
        Long userId = 1L;  // 实际项目中应该查询数据库获取
        
        // 创建新卡
        Card card = new Card();
        card.setCardNo(cardNo);
        card.setUserId(userId);
        card.setIcType(icType);
        card.setCardStatus("正常");
        card.setBalance(new BigDecimal(balance != null ? balance : 0));
        card.setCreateTime(LocalDateTime.now());
        
        // 保存到数据库
        save(card);
        
        return card;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cardLoss(Long cardId) {
        if (cardId == null) {
            return false;
        }
        
        Card card = getById(cardId);
        if (card == null || !"正常".equals(card.getCardStatus())) {
            return false;
        }
        
        card.setCardStatus("挂失");
        return updateById(card);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cardUnLoss(Long cardId) {
        if (cardId == null) {
            return false;
        }
        
        Card card = getById(cardId);
        if (card == null || !"挂失".equals(card.getCardStatus())) {
            return false;
        }
        
        card.setCardStatus("正常");
        return updateById(card);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cardCancel(Long cardId) {
        if (cardId == null) {
            return false;
        }
        
        Card card = getById(cardId);
        if (card == null || "注销".equals(card.getCardStatus())) {
            return false;
        }
        
        card.setCardStatus("注销");
        return updateById(card);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean recharge(String cardNo, Double amount) {
        if (StrUtil.isBlank(cardNo) || amount == null || amount <= 0) {
            return false;
        }
        
        // 查询卡片
        Card card = getOne(Wrappers.<Card>lambdaQuery().eq(Card::getCardNo, cardNo));
        if (card == null || !"正常".equals(card.getCardStatus())) {
            return false;
        }
        
        // 执行充值
        BigDecimal newBalance = card.getBalance().add(new BigDecimal(amount));
        card.setBalance(newBalance);
        
        return updateById(card);
    }
}
